/**
 * 
 */
package yicheng.dinnertogetherapp;


import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import yicheng.dinnertogetherapp.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author Yicheng
 *
 */
public class ConfirmationCodeActivity extends Activity{
	//UI blocks 
	Button code_confirm_button;
	EditText confirmation_code_input_editText;
	TextView confirmation_code_title_textView;
	
	RelativeLayout confirmation_view;
	LinearLayout set_up_database_loading_layout;
	
	//New user register information
	String PHONE_NUMBER;
	String PASSWORD;
	String NICKNAME;
	String GENERATED_CONFIRMATION_CODE;
	//String PRIMARY_PHONE_NUMBER;
	
	
	
	SharedPreferences local_user_information;
	SharedPreferences.Editor local_user_editor;
	String PREFS_NAME = "LocalUserInfo";
	
	Handler handler;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
		
		
		//Pass new user register information from previous New User Register activity
		Intent intent = getIntent();
		Bundle registerInfoData = intent.getBundleExtra("RegisterInformaionData");
		PHONE_NUMBER = registerInfoData.getString("PhoneNumber");
		PASSWORD = registerInfoData.getString("Password");
		NICKNAME = registerInfoData.getString("Nickname");
		GENERATED_CONFIRMATION_CODE = registerInfoData.getString("GeneratedConfirmationCode");
		
		//Set initial content view 
		setContentView(R.layout.confirmation_code_view);
		
		local_user_information =  this.getSharedPreferences(PREFS_NAME,0);
		local_user_editor = local_user_information.edit();
		
		//Load UI in xml into java
		code_confirm_button = (Button) findViewById(R.id.code_input_confirm_button);
		
		
		confirmation_code_input_editText = (EditText) findViewById(R.id.confirmation_code_input_editText);
		confirmation_code_title_textView = (TextView) findViewById(R.id.confirmation_code_title_textView);
		
		confirmation_view = (RelativeLayout) findViewById(R.id.confirmation_view);
		set_up_database_loading_layout = (LinearLayout) findViewById(R.id.set_up_database_loading_layout);
		set_up_database_loading_layout.setVisibility(View.INVISIBLE);
		
		
		
		confirmation_view.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				hideKeyboard();
				return false;
			}
		});
		
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == 1){
					
					//set true when database is loaded 
					Intent gotoUserMainTabActivityIntent = new Intent("yicheng.dinnertogetherapp.USERMAINTABVIEWACTIVITY");
					startActivity(gotoUserMainTabActivityIntent);
					finish();
			
				}
			}
		};
		
		
		
		//Set confirm button action
		code_confirm_button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				hideKeyboard();
			
				if (isInputConfirmationCodeCorrect()){
					
					Toast.makeText(ConfirmationCodeActivity.this, "register successfully!", Toast.LENGTH_SHORT).show();
					
					//Save local user data into shared preference
					local_user_editor.putBoolean("notRegistered", false);
					local_user_editor.putString("PhoneNumber", PHONE_NUMBER);
					local_user_editor.putString("Password", PASSWORD);
					local_user_editor.putString("Nickname", NICKNAME);
					//local_user_editor.putString("primaryPhoneNumber", PHONE_NUMBER);
					//local_user_editor.putString("primaryNickname", NICKNAME);
					local_user_editor.commit();
					
					Animation animationFadeIn = AnimationUtils.loadAnimation(getBaseContext(), R.anim.fade_in);
					set_up_database_loading_layout.startAnimation(animationFadeIn);
					
					
					set_up_database_loading_layout.setVisibility(View.VISIBLE);
					code_confirm_button.setVisibility(View.INVISIBLE);
					confirmation_code_title_textView.setVisibility(View.INVISIBLE);
					confirmation_code_input_editText.setVisibility(View.INVISIBLE);
					
					
					
				/*	Intent gotoUserMainActivityIntent = new Intent("com.example.dinnertogetherapp.LOGINACTIVITY");
					startActivity(gotoUserMainActivityIntent);*/
				
					runOnUiThread(new Runnable(){
						
						public void run() {
							
							Thread setupDBThread = new Thread(new Runnable(){
								
								public void run() {
									
									
									
									setUpNewUserInfoInDB();
									//Toast.makeText(ConfirmationCodeActivity.this, "error loading database", Toast.LENGTH_SHORT).show();
									

									Message msg = Message.obtain();
									msg.what = 1;
									handler.sendMessage(msg);
									
									
								}
								
							});
							
							setupDBThread.start();
						}	
					});
					
					
					
					
				
					
					
				}
				else{
					//Initialize and show notification dialog
					AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(ConfirmationCodeActivity.this);
					dialogBuilder.setTitle("Wrong Confirmation Code");
					dialogBuilder.setMessage("The confirmation code you input is not correct, please check");
					dialogBuilder.setCancelable(true);
					dialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which)  {
							
							dialog.cancel();		
							
						}
					});
					
					AlertDialog dialog = dialogBuilder.create();
					dialog.show();

				}
				
			}

		/*	private SharedPreferences getPreferences(int modePrivate) {
				// TODO Auto-generated method stub
				return null;
			}
*/
			
			
			
			
			
		});
		
		
		
		
		
		
	}
	
	//Judge if the input confirmation is the correct one
	private boolean isInputConfirmationCodeCorrect(){
		return confirmation_code_input_editText.getText().toString().equals(GENERATED_CONFIRMATION_CODE);
	}
	
	
	
	//Set up new user information in the database
	private void setUpNewUserInfoInDB(){
		//Create the new user domain, domain name is the phone number
		SimpleDB.createDomain(LogInActivity.clientManager,PHONE_NUMBER);
		//SimpleDB.deleteDomain(this.PHONE_NUMBER);
		//Create password item, with password attribute 
		SimpleDB.createItem(LogInActivity.clientManager, this.PHONE_NUMBER, SimpleDB.PASSWORD_ITEM);
		HashMap<String, String> password = new HashMap<String, String>();
		password.put(SimpleDB.PASSWORD_ATTRIBUTE, this.PASSWORD);
		password.put("dummyAttribute", "");
		SimpleDB.updateAttributesForItem(LogInActivity.clientManager, this.PHONE_NUMBER,SimpleDB.PASSWORD_ITEM, password);
		
		//Create nickname item, with nickname attribute
		SimpleDB.createItem(LogInActivity.clientManager, this.PHONE_NUMBER, SimpleDB.NICKNAME_ITEM);
		HashMap<String, String> nickname = new HashMap<String, String>();
		nickname.put(SimpleDB.NICKNAME_ATTRIBUTE, this.NICKNAME);
		nickname.put("dummyAttribute", "");
		SimpleDB.updateAttributesForItem(LogInActivity.clientManager, this.PHONE_NUMBER, SimpleDB.NICKNAME_ITEM, nickname);
		
		//Create photoUrl item, with photoUrl attribute
		SimpleDB.createItem(LogInActivity.clientManager, this.PHONE_NUMBER, SimpleDB.PHOTO_URL_ITEM);
		HashMap<String, String> photoUrl = new HashMap<String, String>();
		photoUrl.put(SimpleDB.PHOTO_URL_ATTRIBUTE, "url");
		photoUrl.put("dummyAttribute", "");
		SimpleDB.updateAttributesForItem(LogInActivity.clientManager, this.PHONE_NUMBER, SimpleDB.PHOTO_URL_ITEM, photoUrl);
		
		
		
		
		
		//Create online item, with online attribute, has two values, "online" or "offline"
		SimpleDB.createItem(LogInActivity.clientManager, this.PHONE_NUMBER, SimpleDB.ONLINE_ITEM);
		HashMap<String, String> online = new HashMap<String, String>();
		online.put(SimpleDB.ONLINE_ATTRIBUTE, "offline");
		online.put("dummyAttribute", "");
		SimpleDB.updateAttributesForItem(LogInActivity.clientManager, this.PHONE_NUMBER, SimpleDB.ONLINE_ITEM, online);
		
		
		
		
		
		
		
		
		//Create availability item, with  start time attribute and end time attribute
		
		Calendar currentCal = Calendar.getInstance();

		int curYear = currentCal.get(Calendar.YEAR);
		int curMonth = currentCal.get(Calendar.MONTH);
		int curDay = currentCal.get(Calendar.DAY_OF_MONTH);
		int curHour = currentCal.get(Calendar.HOUR);
		int curMin = currentCal.get(Calendar.MINUTE);

		Date currentDate = new Date(curYear, curMonth, curDay , curHour, curMin);
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("yy/MM/dd h:mm a");
		SimpleDateFormat dayOfWeekFormat = new SimpleDateFormat("EE");
		Date dayOfWeekDate = new Date(curYear, curMonth, curDay - 1);

		String dayOfWeekText = dayOfWeekFormat.format(dayOfWeekDate);


		String current_time = dateFormat.format(currentDate);
		
		
		SimpleDB.createItem(LogInActivity.clientManager, this.PHONE_NUMBER, SimpleDB.AVAILABILITY_ITEM);
		HashMap<String, String> availability = new HashMap<String, String>();
		availability.put(SimpleDB.START_TIME_ATTRIBUTE, dayOfWeekText + ", " + current_time);
		availability.put(SimpleDB.END_TIME_ATTRIBUTE, dayOfWeekText + ", " + current_time);
		SimpleDB.updateAttributesForItem(LogInActivity.clientManager, this.PHONE_NUMBER, SimpleDB.AVAILABILITY_ITEM, availability);
		
		local_user_information =  this.getSharedPreferences(PREFS_NAME,0);
		local_user_editor = local_user_information.edit();
		local_user_editor.putString("start_time", dayOfWeekText + ", " + current_time);
		local_user_editor.putString("end_time", dayOfWeekText + ", " + current_time);
		
		
		local_user_editor.putString("start_year", String.valueOf(curYear));
		local_user_editor.putString("start_month", String.valueOf(curMonth));
		local_user_editor.putString("start_day", String.valueOf(curDay));
		local_user_editor.putString("start_hour", String.valueOf(curHour));
		local_user_editor.putString("start_min", String.valueOf(curMin));
		
		
		
		
		
		
		local_user_editor.putString("end_year", String.valueOf(curYear));
		local_user_editor.putString("end_month", String.valueOf(curMonth));
		local_user_editor.putString("end_day", String.valueOf(curDay));
		local_user_editor.putString("end_hour", String.valueOf(curHour));
		local_user_editor.putString("end_min", String.valueOf(curMin));


		local_user_editor.commit();
		
		
		
		//Create preference item, with preference attribute
		SimpleDB.createItem(LogInActivity.clientManager, this.PHONE_NUMBER, SimpleDB.PREFERENCE_ITEM);
		HashMap<String, String> preference = new HashMap<String, String>();
		preference.put(SimpleDB.PREFERENCE_ATTRIBUTE, "");
		preference.put("dummyAttribute", "");
		
		SimpleDB.updateAttributesForItem(LogInActivity.clientManager, this.PHONE_NUMBER, SimpleDB.PREFERENCE_ITEM, preference);
		
		//Create friend list item, initially no attributes, can add attributes later, each
		//friend's phone number is an attribute and corresponding value is the nickname
		SimpleDB.createItem(LogInActivity.clientManager, this.PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM);
		HashMap<String, String> friendList = new HashMap<String, String>();
		friendList.put("2060000000", "dummyUser");
		SimpleDB.updateAttributesForItem(LogInActivity.clientManager, this.PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM, friendList);
		
		//Create friend request list item, initially no attributes, can add later, each 
		//friend's phone number is an attribute and corresponding value is the nickname
		SimpleDB.createItem(LogInActivity.clientManager, this.PHONE_NUMBER, SimpleDB.FRIEND_REQUEST_LIST_ITEM);
		HashMap<String, String> friendRequestList = new HashMap<String, String>();
		friendRequestList.put("2060000000", "dummyUser");
		
		SimpleDB.updateAttributesForItem(LogInActivity.clientManager, this.PHONE_NUMBER, SimpleDB.FRIEND_REQUEST_LIST_ITEM, friendRequestList);
		
	
		
		//Create be unavailable to list item, can add later, each friend's phone number is 
		//an attribute and corresponding value is the nickname
		SimpleDB.createItem(LogInActivity.clientManager, this.PHONE_NUMBER, SimpleDB.BE_UNAVAILABLE_TO_LIST_ITEM);
		HashMap<String, String> beUnavailableToList = new HashMap<String, String>();
		beUnavailableToList.put("2060000000", "dummyUser");
		
		SimpleDB.updateAttributesForItem(LogInActivity.clientManager, this.PHONE_NUMBER, SimpleDB.BE_UNAVAILABLE_TO_LIST_ITEM, beUnavailableToList);
		
		//Create online friend list item, add later, each friend's phone number is an 
		//attribute and corresponding value is the nickname
		SimpleDB.createItem(LogInActivity.clientManager, this.PHONE_NUMBER, SimpleDB.ONLINE_FRIEND_LIST_ITEM);
		HashMap<String, String> onlineFriendList = new HashMap<String, String>();
		onlineFriendList.put("2060000000", "dummyUser");
		SimpleDB.updateAttributesForItem(LogInActivity.clientManager, this.PHONE_NUMBER, SimpleDB.ONLINE_FRIEND_LIST_ITEM, onlineFriendList);
		
		//Create offline friend list item, add later, each friend's phone number is an
		//attribute and corresponding value is the nickname
		SimpleDB.createItem(LogInActivity.clientManager, this.PHONE_NUMBER, SimpleDB.OFFLINE_FRIEND_LIST_ITEM);
		HashMap<String, String> offlineFriendList = new HashMap<String, String>();
		offlineFriendList.put("2060000000", "dummyUser");
		SimpleDB.updateAttributesForItem(LogInActivity.clientManager, this.PHONE_NUMBER, SimpleDB.OFFLINE_FRIEND_LIST_ITEM, offlineFriendList);
		
		
		
		
		
		
	}
	
	
	
	
	
	//Set back button action, when user press back button, application won't terminate,
	//just switch out to the home
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		moveTaskToBack(true);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK ) {
	        //preventing default implementation previous to 
	        //android.os.Build.VERSION_CODES.ECLAIR
			moveTaskToBack(true);
	        return false;
	    }     
	    return super.onKeyDown(keyCode, event);    
	}
	
	private void hideKeyboard(){
		if(getCurrentFocus()!=null) {
			InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
		}
	}

	
	

}
